<?php
/**
 * Created by PhpStorm.
 * User: marin
 * Date: 2020/9/9
 * Time: 下午3:09
 */

namespace app\common\model;


use app\common\logic\WxPayConfig;
use think\Log;
use think\Model;
use YouGeCore\Wx\Pay\Exception\WxPayException;
use YouGeCore\Wx\Pay\Lib\WxPayRefund;
use YouGeCore\Wx\WxPayApiAop;

class Wxpay extends Model
{
    /**
     *
     * @param $orderId
     * @param $amount
     * @return bool
     */
    public function refundToUser($orderId,$amount)
    {
        /** @var \app\common\model\Order $orderModel */
        $order = db('order')->where('order_id',$orderId)->find();

        $orderPay = db('orderpay')->where('pay_sn',$order['pay_sn'])->field('*')->select();
        if (!$orderPay){
            exception('没有找到支付信息');
        }
        $orderPay = array_pop($orderPay);


        $transaction_id = $orderPay['trade_no'];

        $wxPayApiAop = new WxPayApiAop();

        $wxPayRefund = new WxPayRefund();
        $wxPayRefund->SetTransaction_id($transaction_id);
        $wxPayRefund->SetTotal_fee($amount*100);//单位由元转化成分
        $wxPayRefund->SetRefund_fee($amount*100);//全退

        $wxPayConfig = new WxPayConfig();
        $wxPayRefund->SetOut_refund_no($order['order_sn']);
        $wxPayRefund->SetOp_user_id($wxPayConfig->GetMerchantId());
        try {
            $result = $wxPayApiAop->applyWxRefund($wxPayConfig, $wxPayRefund);
            Log::info("退款结果:".is_array($result) ? json_encode($result):$result,'debug');
            if ($result['return_code'] === 'SUCCESS'){
                if ($result['result_code']==='SUCCESS'){
                    return true;
                }elseif ($result['result_code'] === 'FAIL'){
                    exception($result['err_code_des']);
                }
            }else{
                exception('请求微信退款失败');
            }
        } catch (WxPayException $e) {
            Log::info("退款异常:".$e->getMessage(),'debug');
            exception($e->getMessage());
        }
//

    }
}